package com.firefightingiot.firefightingiot.support.utils.json;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 将json的key全部转化成转驼峰之后的
 */
public class JsonKeyEdit {

    public static String jsonKeyEdit(String jsonStr){

        //转换后的字符串
        String str = jsonStr;

        //满足json字符串key的正则
        String regx = "\"\\w+\":";

        //1.将正在表达式封装成对象Patten 类来实现
        Pattern pattern = Pattern.compile(regx);

        //2.将字符串和正则表达式相关联
        Matcher matcher = pattern.matcher(jsonStr);

        //查找符合规则的子串
        while(matcher.find()){

            //获取的字符串的首位置和末位置 以及 获取 字符串
            System.out.println(matcher.start()+"--"+matcher.end()+" : "+matcher.group());
            //输出一下信息
            //1--10 : "status":
            //12--19 : "code":
            //26--36 : "message":
            //41--48 : "data":
            //49--62 : "buy_status":
            //66--80 : "track_price":
            //84--101 : "track_buy_tips":
            //133--142 : "tracks":
            //144--158 : "is_purchase":
            //162--171 : "pinyin":
            //183--197 : "is_purchase":
            //201--210 : "pinyin":

            //取代下划线命名的key为驼峰命名的key
            //ToCamelCase类中camelCase方法将下划线命名转驼峰命名
            //具体代码请移步上一篇文章 http://blog.csdn.net/qq_25386583/article/details/77001126
            str = str.replaceFirst(matcher.group(),camelCase(matcher.group()));
            System.out.println(str);
        }

        return str;
    }

    /**
     * _aa__Bc_C_c_  ==>  aaBcCc
     * @param str
     * @return 驼峰命名字符串
     */
    public static String camelCase(String str){
        if(str==null||!str.contains("_")){
            return str;
        }
        String camelCase = "";
        String[] arr = str.split("_");
        List<String> list = new ArrayList<String>();

        //将数组中非空字符串添加至list
        for(String a : arr){
            if(a.length() > 0){
                list.add(a);
            }
        }

        for(int i=0;i<list.size();i++){
            if(i>0){    //后面单词首字母大写
                char c = list.get(i).charAt(0);
                String s = String.valueOf(c).toUpperCase() + list.get(i).substring(1).toLowerCase();
                camelCase+=s;
            }else{  //首个单词小写
                camelCase+=list.get(i).toLowerCase();
            }
        }
        return camelCase;
    }

    public static void main(String[] args) {
        String jsonStr = "上面的json字符串,这里就别copy了";

        System.out.println((jsonKeyEdit(jsonStr)));

    }
}
